package com.slf.engine.services.impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.text.html.HTML.Tag;

import org.apache.commons.httpclient.NameValuePair;
import org.apache.log4j.Logger;
import org.apache.log4j.Priority;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;
import com.slf.engine.bo.Order;
import com.slf.engine.common.SysContants;
import com.slf.engine.exception.EngineException;
import com.slf.engine.http.HttpClientManager;
import com.slf.engine.http.HttpResponseWrapper;
import com.slf.engine.services.IBjdxService;
import com.slf.engine.services.helper.ServiceHelper;
import com.slf.engine.utils.ConnectUtil;
import com.slf.engine.utils.DateUtils;

public class BjdxServiceImpl implements IBjdxService {

	private static final Logger log  = Logger.getLogger(BjdxServiceImpl.class);
	
	public boolean doLogin()
	{
		String ViewState = null;
		try {
			HttpResponseWrapper wrapper = ConnectUtil.getInStantic().execute("GET", SysContants.VAMS_LOGIN_URL, SysContants.DEFAULT_CHARSET, null, null, null, null, null);
			if(wrapper.getBody() == null)
			{
				return doLogin();
			}
			
			String body = new String(wrapper.getBody(),SysContants.DEFAULT_CHARSET);
			HtmlCleaner cleaner = new HtmlCleaner();
			TagNode bodyNode = cleaner.clean(body);
			Object obj[] = bodyNode.evaluateXPath("//form[@id='login']/input[@name='javax.faces.ViewState']");
			if(obj !=null && obj.length > 0)
			{
				TagNode node = (TagNode)obj[0];
				ViewState = node.getAttributeByName("value");
			}
		} catch (EngineException e) {
			// TODO Auto-generated catch block
			return doLogin();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
		} catch (IOException e) {
			// TODO Auto-generated catch block
		} catch (XPatherException e) {
			// TODO Auto-generated catch block
		}
		
		if(ViewState != null)
		{
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			NameValuePair javax_faces_ViewState = new NameValuePair("javax.faces.ViewState",ViewState);
			NameValuePair login = new NameValuePair("login","login");
			NameValuePair hiddenValue = new NameValuePair("login:hiddenValue","");
			NameValuePair x = new NameValuePair("login:j_id_jsp_28762255_4.x","25");
			NameValuePair y = new NameValuePair("login:j_id_jsp_28762255_4.y","11");
			NameValuePair password = new NameValuePair("login:password",SysContants.VAMS_PASSWORD);
			NameValuePair userName = new NameValuePair("login:userName",SysContants.VAMS_LOGINNAME);
			params.add(javax_faces_ViewState);
			params.add(login);
			params.add(hiddenValue);
			params.add(x);
			params.add(y);
			params.add(password);
			params.add(userName);
			
			try {
				ConnectUtil.getInStantic().execute("POST", SysContants.VAMS_LOGIN_URL, SysContants.DEFAULT_CHARSET, null, null, params, null, null);
				HttpResponseWrapper wrapper = ConnectUtil.getInStantic().execute("GET", "http://219.141.157.23/vams/header.jsp", SysContants.DEFAULT_CHARSET, null, null, null, null, null);
				if(wrapper.getBody() == null)
				{
					return doLogin();
				}
				String body = new String(wrapper.getBody(),SysContants.DEFAULT_CHARSET);
				
				if(body.indexOf(SysContants.VAMS_LOGINNAME) != -1)
				{
					log.log(Priority.INFO, "北京电信登录成功");
					return true;
				}
			} catch (EngineException e) {
				// TODO Auto-generated catch block
				return doLogin();
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
			}
		}else{
			doLogin();
		}
		return false;
	}
	
	/**
	 * 交易线程
	 */
	public Order doPay(Order order,HttpClientManager manager,boolean isCDMA)
	{
		String body = "";
		log.log(Priority.INFO, "正在处理交易account：" + order.getAccount() + " orderId:" + order.getOrderId());
		String ViewState =null;
		try {
			HttpResponseWrapper wrapper = manager.execute("GET", SysContants.VAMS_PAY_URL, SysContants.DEFAULT_CHARSET, null, null, null, null, null);
			if(wrapper.getBody() == null)
			{
				return doPay(order, manager, isCDMA);
			}
			body = new String(wrapper.getBody(),SysContants.DEFAULT_CHARSET);
			HtmlCleaner cleaner = new HtmlCleaner();
			TagNode bodyNode = cleaner.clean(body);
			Object obj[] = bodyNode.evaluateXPath("//form[@id='webPayment']/table/tbody/tr/td/input[@name='javax.faces.ViewState']");
			if(obj !=null && obj.length > 0)
			{
				TagNode node = (TagNode)obj[0];
				ViewState = node.getAttributeByName("value");
			}
		} catch (EngineException e) {
			// TODO Auto-generated catch block
			log.log(Priority.INFO, "进入上游充值页面发生错误，重新发起");
			return doPay(order, manager, isCDMA);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
		} catch (IOException e) {
			// TODO Auto-generated catch block
		} catch (XPatherException e) {
			// TODO Auto-generated catch block
		}
		
		if(ViewState != null)
		{
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			NameValuePair javax_faces_ViewState = new NameValuePair("javax.faces.ViewState",ViewState);
			NameValuePair webPayment = new NameValuePair("webPayment","webPayment");
			NameValuePair j_id_jsp_427518967_10 = null;
			try {
				j_id_jsp_427518967_10 = new NameValuePair("webPayment:j_id_jsp_427518967_10",URLEncoder.encode("充值", SysContants.DEFAULT_CHARSET));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
			}
			NameValuePair mess = new NameValuePair("webPayment:mess","");
			NameValuePair transAmount = new NameValuePair("webPayment:transAmount",order.getMoney());
			NameValuePair transNumber = new NameValuePair("webPayment:transNumber",order.getAccount());
			NameValuePair transPassword = new NameValuePair("webPayment:transPassword",SysContants.VAMS_PAYPWD);
			params.add(javax_faces_ViewState);
			params.add(webPayment);
			params.add(j_id_jsp_427518967_10);
			params.add(mess);
			params.add(transAmount);
			params.add(transNumber);
			params.add(transPassword);
			try {
				HttpResponseWrapper wrapper = manager.execute("POST", SysContants.VAMS_PAY_URL, SysContants.DEFAULT_CHARSET, null, null, params, null, null);
				if(wrapper.getBody() == null)
				{
					//需要查询
					order.setClbz(SysContants.CZ_RUN);
					return order;
				}
				body = new String(wrapper.getBody(),SysContants.DEFAULT_CHARSET);
				if(body.indexOf("webPayment:mess") != -1)
				{
					HtmlCleaner cleaner = new HtmlCleaner();
					TagNode bodyNode = cleaner.clean(body);
					body = cleaner.getInnerHtml(bodyNode);
					log.log(Priority.INFO,"充值返回：" + body);
					if(body.indexOf("错误代码") != -1)
					{
						order.setClbz(SysContants.CZ_FAILURE);
						order.setCljg("充值失败");
					}else if(body.indexOf("充值成功") != -1){
						order.setClbz(SysContants.CZ_SUCCESS);
						order.setCljg("充值成功,当前账户余额：" + queryYe(manager));
					}else{
						order.setClbz(SysContants.CZ_RUN);
					}
				}else{
					order.setClbz(SysContants.CZ_RUN);
				}
				return order;
			} catch (EngineException e) {
				// TODO Auto-generated catch block
				order.setClbz(SysContants.CZ_RUN);
				
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
			} catch (IOException e) {
				// TODO Auto-generated catch block
			} 
		}else{
			log.log(Priority.INFO, "交易错误返回：" + body);
			if(body.indexOf("无权访问") != -1)
			{
				if(doLogin())
				{
					return doPay(order, manager, isCDMA);
				}
			}else{
				order.setClbz(SysContants.CZ_UNKNOW);
				order.setCljg("充值失败,上游网站访问超时");
			}
		
			return order;
		}
		
		return order;
	}
	
	/**
	 * 订单查询
	 * @param order
	 * @param manager
	 * @return
	 */
	public Order doQuery(Order order, HttpClientManager manager)
	{
		String ViewState = null;
		try {
			HttpResponseWrapper wrapper = manager.execute("GET", SysContants.VAMS_QUERY_URL, SysContants.DEFAULT_CHARSET, null, null, null, null, null);
			if(wrapper.getBody() == null)
			{
				return doQuery(order, manager);
			}
			String body = new String(wrapper.getBody(),SysContants.DEFAULT_CHARSET);
			HtmlCleaner cleaner = new HtmlCleaner();
			TagNode bodyNode = cleaner.clean(body);
			Object obj[] = bodyNode.evaluateXPath("//form[@id='form1']/table/tbody/tr/td/input[@name='javax.faces.ViewState']");
			if(obj !=null && obj.length > 0)
			{
				TagNode node = (TagNode)obj[0];
				ViewState = node.getAttributeByName("value");
			}
		} catch (EngineException e) {
			// TODO Auto-generated catch block
			return doQuery(order, manager);		
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
		} catch (IOException e) {
			// TODO Auto-generated catch block
		} catch (XPatherException e) {
			// TODO Auto-generated catch block
		}
		
		if(ViewState != null)
		{
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			NameValuePair javax_faces_ViewState = new NameValuePair("javax.faces.ViewState",ViewState);
			NameValuePair form1 = new NameValuePair("form1","form1");
			NameValuePair cgiAccessType = new NameValuePair("form1:cgiAccessType","-1");
			NameValuePair cgiChargeStatus = new NameValuePair("form1:cgiChargeStatus","-1");
			NameValuePair cgiServiceno = new NameValuePair("form1:cgiServiceno","-1");
			NameValuePair j_id_jsp_1155368641_4 = new NameValuePair("form1:j_id_jsp_1155368641_4",SysContants.VAMS_CODE_NUM);
			NameValuePair j_id_jsp_1155368641_8 = new NameValuePair("form1:j_id_jsp_1155368641_8","");
			NameValuePair j_id_jsp_1155368641_9 = new NameValuePair("form1:j_id_jsp_1155368641_9",DateUtils.strDate("yyyy/MM/dd"));
			NameValuePair j_id_jsp_1155368641_11 = new NameValuePair("form1:j_id_jsp_1155368641_11",DateUtils.strDate("yyyy/MM/dd"));
			NameValuePair j_id_jsp_1155368641_13 = new NameValuePair("form1:j_id_jsp_1155368641_13","");
			NameValuePair j_id_jsp_1155368641_32 = null;
			try {
				j_id_jsp_1155368641_32 = new NameValuePair("form1:j_id_jsp_1155368641_32",URLEncoder.encode("查询", SysContants.DEFAULT_CHARSET));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
			}
			NameValuePair payNo = new NameValuePair("form1:payNo",order.getAccount());
			
			params.add(javax_faces_ViewState);
			params.add(form1);
			params.add(cgiAccessType);
			params.add(cgiChargeStatus);
			params.add(cgiServiceno);
			params.add(j_id_jsp_1155368641_4);
			params.add(j_id_jsp_1155368641_8);
			params.add(j_id_jsp_1155368641_9);
			params.add(j_id_jsp_1155368641_11);
			params.add(j_id_jsp_1155368641_13);
			params.add(j_id_jsp_1155368641_32);
			params.add(payNo);
			
			try {
				HttpResponseWrapper wrapper = manager.execute("POST", SysContants.VAMS_QUERY_URL, SysContants.DEFAULT_CHARSET, null, null, params, null, null);
				if(wrapper.getBody() == null)
				{
					return doQuery(order, manager);
				}
				String body = new String(wrapper.getBody(),SysContants.DEFAULT_CHARSET);
				HtmlCleaner cleaner = new HtmlCleaner();
				TagNode bodyNode = cleaner.clean(body);
				//log.log(Priority.INFO, "查询返回:" + body);
				Object obj[] = bodyNode.evaluateXPath("//form[@id='agentQry']/div[@align='center']/table/tbody/tr");
				if(obj != null && obj.length > 0)
				{
					for(int i = 0; i < obj.length;i++)
					{
						TagNode node = (TagNode)obj[i];
						Object td1[] = node.evaluateXPath("//td[@class='standardTable_column3']/div[@align='center']/text()");
						if(td1 != null && td1.length > 0)
						{
							String bczsjh = ((StringBuffer)td1[0]).toString().trim();
							td1 = node.evaluateXPath("//td[@class='standardTable_column4']/text()");
							String czje = ((StringBuffer)td1[0]).toString();
							if(bczsjh.equals(order.getAccount()) && czje.equals(order.getMoney()))
							{
								td1 = node.evaluateXPath("//td[@class='standardTable_column7']/text()");
								String cljg = ServiceHelper.getBackMsg(((StringBuffer)td1[0]).toString());
								if(cljg.equals("成功"))
								{
									order.setClbz(SysContants.CZ_SUCCESS);
									order.setCljg(cljg);
								}else if(cljg.indexOf("失败") != -1){
									order.setClbz(SysContants.CZ_FAILURE);
									order.setCljg(cljg);
								}else{
									order.setClbz(SysContants.CZ_UNKNOW);
									order.setCljg(cljg);
								}
								return order;
							}
						}
					}
				}
			} catch (EngineException e) {
				// TODO Auto-generated catch block
				return doQuery(order, manager);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
			} catch (IOException e) {
				// TODO Auto-generated catch block
			} catch (XPatherException e) {
				// TODO Auto-generated catch block
			}
		}else{
			doQuery(order, manager);
		}
		return null;
	}
	
	
	private String queryYe(HttpClientManager manager)
	{
		String ViewState = null;
		try {
			HttpResponseWrapper wrapper = manager.execute("GET", SysContants.VAMS_YE_URL, SysContants.DEFAULT_CHARSET, null, null, null, null, null);
			if(wrapper.getBody() == null)
			{
				return queryYe(manager);
			}
			String body = new String(wrapper.getBody(),SysContants.DEFAULT_CHARSET);
			HtmlCleaner cleaner = new HtmlCleaner();
			TagNode bodyNode = cleaner.clean(body);
			Object obj[] = bodyNode.evaluateXPath("//form[@id='j_id_jsp_1894475275_1']/input[@name='javax.faces.ViewState']");
			if(obj !=null && obj.length > 0)
			{
				TagNode node = (TagNode)obj[0];
				ViewState = node.getAttributeByName("value");
			}
		} catch (EngineException e) {
			// TODO Auto-generated catch block
			return queryYe(manager);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
		} catch (IOException e) {
			// TODO Auto-generated catch block
		} catch (XPatherException e) {
			// TODO Auto-generated catch block
		}
		
		if(ViewState != null)
		{
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			NameValuePair javax_faces_ViewState = new NameValuePair("javax.faces.ViewState",ViewState);
			NameValuePair j_id_jsp_1894475275_1 = new NameValuePair("j_id_jsp_1894475275_1","j_id_jsp_1894475275_1");
			NameValuePair j_id_jsp_1894475275_4 = new NameValuePair("j_id_jsp_1894475275_1:j_id_jsp_1894475275_4",SysContants.VAMS_CODE_NUM);
			NameValuePair j_id_jsp_1894475275_6 = new NameValuePair("j_id_jsp_1894475275_1:j_id_jsp_1894475275_6","");
			NameValuePair j_id_jsp_1894475275_8 = new NameValuePair("j_id_jsp_1894475275_1:j_id_jsp_1894475275_8","1");
			NameValuePair j_id_jsp_1894475275_11 = new NameValuePair("j_id_jsp_1894475275_1:j_id_jsp_1894475275_11","-1");
			NameValuePair j_id_jsp_1894475275_15 = new NameValuePair("j_id_jsp_1894475275_1:j_id_jsp_1894475275_15","");
			NameValuePair j_id_jsp_1894475275_17 = new NameValuePair("j_id_jsp_1894475275_1:j_id_jsp_1894475275_17","");
			NameValuePair j_id_jsp_1894475275_19 = new NameValuePair("j_id_jsp_1894475275_1:j_id_jsp_1894475275_19","");
			NameValuePair j_id_jsp_1894475275_21 = new NameValuePair("j_id_jsp_1894475275_1:j_id_jsp_1894475275_21","");
			NameValuePair j_id_jsp_1894475275_23 = new NameValuePair("j_id_jsp_1894475275_1:j_id_jsp_1894475275_23","");
			NameValuePair j_id_jsp_1894475275_25 = new NameValuePair("j_id_jsp_1894475275_1:j_id_jsp_1894475275_25","");
			NameValuePair j_id_jsp_1894475275_27 = new NameValuePair("j_id_jsp_1894475275_1:j_id_jsp_1894475275_27","0");
			NameValuePair j_id_jsp_1894475275_31 = new NameValuePair("j_id_jsp_1894475275_1:j_id_jsp_1894475275_31","");
			NameValuePair j_id_jsp_1894475275_32 = null;
			try {
				j_id_jsp_1894475275_32 = new NameValuePair("j_id_jsp_1894475275_1:j_id_jsp_1894475275_32",URLEncoder.encode("",SysContants.DEFAULT_CHARSET));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
			}
			params.add(javax_faces_ViewState);
			params.add(j_id_jsp_1894475275_1);
			params.add(j_id_jsp_1894475275_4);
			params.add(j_id_jsp_1894475275_6);
			params.add(j_id_jsp_1894475275_8);
			params.add(j_id_jsp_1894475275_11);
			params.add(j_id_jsp_1894475275_15);
			params.add(j_id_jsp_1894475275_17);
			params.add(j_id_jsp_1894475275_19);
			params.add(j_id_jsp_1894475275_21);
			params.add(j_id_jsp_1894475275_23);
			params.add(j_id_jsp_1894475275_25);
			params.add(j_id_jsp_1894475275_27);
			params.add(j_id_jsp_1894475275_31);
			params.add(j_id_jsp_1894475275_32);
			
			try {
				HttpResponseWrapper wrapper = manager.execute("POST", SysContants.VAMS_YE_URL, SysContants.DEFAULT_CHARSET, null, null, params, null, null);
				if(wrapper.getBody() == null)
				{
					return queryYe(manager);
				}
				String body = new String(wrapper.getBody(), SysContants.DEFAULT_CHARSET);
				
				if(body.indexOf("共") != -1)
				{
					HtmlCleaner cleaner = new HtmlCleaner();
					TagNode bodyNode = cleaner.clean(body);
					Object obj[] = bodyNode.evaluateXPath("//form[@id='agentQry']/input[@name='javax.faces.ViewState']");
					if(obj !=null && obj.length > 0)
					{
						TagNode node = (TagNode)obj[0];
						ViewState = node.getAttributeByName("value");
					}
					params.clear();
					NameValuePair agentQry = new NameValuePair("agentQry","agentQry");
					NameValuePair j_id_jsp_1894475275_59 = new NameValuePair("agentQry:j_id_jsp_1894475275_35:0:j_id_jsp_1894475275_59","agentQry:j_id_jsp_1894475275_35:0:j_id_jsp_1894475275_59");
					NameValuePair j_id_jsp_1894475275_85 = new NameValuePair("agentQry:j_id_jsp_1894475275_85","1");
					NameValuePair mess = new NameValuePair("agentQry:mess","");
					NameValuePair isSession = new NameValuePair("isSession","yes");
					javax_faces_ViewState = new NameValuePair("javax.faces.ViewState",ViewState);
					NameValuePair viewDetail = new NameValuePair("viewDetail","remain");
					
					params.add(agentQry);
					params.add(j_id_jsp_1894475275_59);
					params.add(j_id_jsp_1894475275_85);
					params.add(mess);
					params.add(isSession);
					params.add(javax_faces_ViewState);
					params.add(viewDetail);
					
					wrapper = manager.execute("POST", SysContants.VAMS_YE_URL, SysContants.DEFAULT_CHARSET, null, null, params,null, null);
					if(wrapper.getBody() == null)
					{
						return queryYe(manager);
					}
					
					body = new String(wrapper.getBody(),SysContants.DEFAULT_CHARSET);
					
					if(body.indexOf("huidi2") != -1)
					{
						bodyNode = cleaner.clean(body);
						obj = bodyNode.evaluateXPath("//div[@id='zhu1']/table/tbody/tr/td[@class='huidi2']/text()");
						if(obj != null && obj.length > 0)
						{
							StringBuffer s = (StringBuffer)obj[0];
							return s.toString().trim().replaceAll("&nbsp;", "");
						}
					}
				}else{
					return queryYe(manager);
				}
			} catch (EngineException e) {
				// TODO Auto-generated catch block
				return queryYe(manager);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
			} catch (IOException e) {
				// TODO Auto-generated catch block
			} catch (XPatherException e) {
				// TODO Auto-generated catch block
			}
		}else{
			return queryYe(manager);
		}
		return null;
	}
	
	public static void main(String args[])
	{
		IBjdxService ievcService = new BjdxServiceImpl();
		if(ievcService.doLogin())
		{
			Order order = new Order();
			order.setMoney("30");
			order.setAccount("15321900201");
			order.setOrderId("1010101010");
			ievcService.doQuery(order,  ConnectUtil.getInStantic());
		}
	}
}
